﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.Net.Sockets;

namespace WOLServer
{
    internal class WOLService
    {
        static object _logLock = new object();
        public static void Log(string msg)
        {
            lock (_logLock)
            {
                var now = DateTime.Now;
                var logFileName = $"log-{now.Year}-{now.Month}-{now.Day}.txt";
                File.AppendAllLines(logFileName, new[] { $"{now}:{msg}" });
            }
        }
        public void Start(string serviceIp,string subnet,int port,int interval)
        {
            IPEndPoint ip = new IPEndPoint(IPAddress.Parse(serviceIp), port);
            var buffer = new byte[1024];
            var wakeUpTime = DateTime.MinValue;
            using (var socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp))
            {
                socket.Bind(ip);
                Log($"Server Has Started! Args:{serviceIp} {subnet} {port} {interval}");
                while (true)
                {
                    try
                    {
                        socket.Receive(buffer);
                        if (DateTime.Now - wakeUpTime < new TimeSpan(0, 0, interval))
                        {
                            continue;
                        }
                        WakeUp(buffer, subnet,port);
                        wakeUpTime=DateTime.Now;
                    }
                    catch (Exception ex)
                    {
                        Log(ex.GetBaseException().ToString());
                    }
                }
            }
        }
        void WakeUp(byte[] magicBytes,string subnet,int port)
        {
            using (UdpClient Client = new UdpClient())
            {
                var point = new IPEndPoint(IPAddress.Parse(subnet), port);
                var len = magicBytes.Length;
                /*
                for (var i = 0; i < magicBytes.Length; i++)
                {
                    if (magicBytes[i] == 0)
                    {
                        break;
                    }
                    len++;
                }
                */
                Log($"Send magicBytes start. Len:{len},Args:{subnet} {port}");
                Client.Send(magicBytes, len, point);
                Log($"Send magicBytes end.Len:{len},Args:{subnet} {port}");
            }
        }
    }
}
